import axios, { AxiosResponse, InternalAxiosRequestConfig } from "axios";
import { ElMessage } from "element-plus";
import { handleUnauthorized } from "@/api/utils/auth";
import userStore from "@/store/user";

// 统一 API 响应类型定义
export interface ApiResponse {
  code: number;
  msg: string;
  data: any;
}

const request = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 10000,
  headers: {
    "Content-Type": "application/json",
  },
});

// 请求拦截器
request.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    if (config.headers["isToken"] !== false) {
      config.headers["Authorization"] = `Bearer ${userStore.state.token}`;
    }
    return config;
  },
  (error) => {
    console.error(error);
    return Promise.reject(error);
  }
);

// 响应拦截器
request.interceptors.response.use(
  <T>(response: AxiosResponse<ApiResponse>) => {
    if (response.status === 200) {
      const { data } = response;
      if (response.request.responseType === "blob") {
        return response;
      }
      if (data.code === 401) {
          handleUnauthorized();
      } else if (data.code !== 200) {
        ElMessage.error(data.msg);
      }
      return response;
    } else {
      ElMessage.error("请求失败，请稍后重试");
      return Promise.reject(new Error("请求失败，请稍后重试"));
    }
  },
  (error) => {
    console.error(error);
    ElMessage.error("网络异常，请稍后再试");
    return Promise.reject(error);
  }
);

export default request;
